#include "GError.h"
#include "GInputDevice.h"
#include "GInputModule.h"
#include "GInputManager.h"

namespace GEngine
{
	G_MODULE_DESCRIPTOR(GInputModule, GModule, NULL);

	GInputModule::GInputModule()
	{
	}

	GInputModule::~GInputModule()
	{
	}
	
	void GInputModule::RegisterDevice(const char* Name, GInputDevice* Device)
	{
		mGInputManager->RegisterDevice(Name, Device);
		ModuleDevices.insert(DeviceMap::value_type(Name, Device));
	}

	void GInputModule::UnregisterDevice(const char* Name)
	{
		ModuleDevices.erase(Name);
		mGInputManager->UnregisterDevice(Name);
	}

	// Finds a device that is owned by the module
	GInputDevice* GInputModule::GetDevice(const char* Name) const
	{
		DeviceMap::const_iterator Iter = ModuleDevices.find(Name);
		return Iter == ModuleDevices.end() ? NULL : Iter->second;
	}

	// Resets all devices owned by this module
	void GInputModule::Reset()
	{
		DeviceMap::iterator End = ModuleDevices.end();
		DeviceMap::iterator Iter = ModuleDevices.begin();
		
		while (Iter != End)
		{
			Iter->second->Reset();

			Iter++;
		}
	}

	// Updates all devices owned by this module
	bool GInputModule::Update(float ElapsedTime) OVERRIDE
	{
		DeviceMap::iterator End = ModuleDevices.end();
		DeviceMap::iterator Iter = ModuleDevices.begin();
		while (Iter != End)
		{
			Iter->second->Update();

			Iter++;
		}

		return true;
	}

	bool GInputModule::Initialize() OVERRIDE
	{
		if (!GModule::Initialize())
		{
			return false;
		}

		ModuleDevices.reserve(8);

		return true;
	}

	void GInputModule::Uninitialize() OVERRIDE
	{
		ModuleDevices.clear();
		GModule::Uninitialize();
	}

}